// pages/foodmanager/recipe/recipe.js
const app = getApp();
const call = require('../../../utils/request.js');
const md5 = require('../../../utils/md5.js');
const utils = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sHeight:app.globalData.sHeight,
    offset: 0,
    timestamp: '',
    deviceCode: '',
    sign: '',
    recipeList: [],
    reqMore: null,
    isLoadBegin:false,
    isLoadFinished: false
  },
  onDetail(e) {
    const recipe = JSON.stringify(e.currentTarget.dataset.recipe);
    console.log('recipe', e.currentTarget.dataset.recipe);
    wx.navigateTo({
      url: '/pages/foodmanager/recipe/detail/detail?d_info=' + recipe,
    })
  },
  onLower() {
    console.log('拖动到底部')
    var that = this;
    if (that.data.isLoadFinished) {
      console.log('没有更多了~')
    } else {
      if (this.data.reqMore) clearInterval(this.data.reqMore)
      this.setData({
        reqMore: setTimeout(function() {
          console.log('到底了')
          that.setData({
            offset: that.data.offset + 10 //查看下一页食谱
          }, () => {
            that._fridgeFoodRecommend();
          })
        }, 500),
        isLoadBegin:true
      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 在组件实例进入页面节点树时执行
    var that = this;
    //计算字段
    const timestamp = utils.dataFormat().time2;
    const deviceCode = app.globalData.mac;
    const sign = md5.hexMD5(`timestamp:${utils.dataFormat()},deviceCode:${app.globalData.mac},ver:v1.0,unilife`);
    this.setData({
      timestamp,
      deviceCode,
      sign
    }, () => {
      //调用设备食材接口
      that._fridgeFoodRecommend()
      //调用所选食材接口
      // that._searchRecipe()
    })
  },
  _fridgeFoodRecommend() {
    var that = this;
    const {
      offset,
      timestamp,
      deviceCode,
      sign
    } = that.data;
    //触发接口
    const url = `/service/app/v1/recipe/fridgeFoodRecommend`;
    const params = {
      "header": {
        "timestamp": timestamp,
        "deviceCode": deviceCode,
        "ver": "v1.0",
        "sign": sign
      },
      "data": {},
      "offset": offset,
      "pageSize": 10
    };
    console.log('接口地址:', url);
    console.log('接口传参:', JSON.stringify(params));
    call.postData(url, params,
      res => {
        if (res.data.length !== 0) {
          console.log('获取食谱成功', res);
          const recipeList = that.data.recipeList.slice();
          that.setData({
            recipeList: recipeList.concat(res.data),
            isLoadBegin:false
          })
        } else {
          console.log('没有食材咯')
          that.setData({
            isLoadFinished: true
          })
        }

      },
      err => {
        console.log('获取食谱失败', err)
      })
  }
})